//
//  ScratchMessage.m
//  EsotericDemo
//
//  Created by Temp Admin on 6/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ScratchMessage.h"

@implementation ScratchMessage

- (id) init 
{
	if (self = [super init]) 
	{
		Data = [[NSMutableData alloc] init];
	}
	return self;
}

- (int) dataSize
{
	return [Data length];
}

- (NSData *) getData
{
	return [[NSData alloc] initWithData:Data];
}

- (void) setFlag : (ushort) newflag : (bool) value
{
	if (value)
		Flags |= newflag;
	else
		Flags &= ~newflag;
}

- (bool) getFlag : (ushort) theflag
{
	return (Flags && theflag) == theflag;
}

- (uint8_t) getByte
{
	if (offset >= [Data length]) 
		return 0;
	uint8_t result;
	[Data getBytes:&result range:NSMakeRange(offset++, 1)];
	return result;
}

- (NSData *) getBytes
{
	NSData * result = [Data subdataWithRange:NSMakeRange(offset, [Data length] - offset)];
	offset = [Data length];
	return result;
}

- (NSData *) getByteLength : (int) length
{
	NSData * result = [Data subdataWithRange:NSMakeRange(offset, length)];
	offset += length;
	return result;
}

- (uint16_t) getShort
{
	if (offset >= [Data length]-1) 
		return 0;
	uint16_t result;
	[Data getBytes:&result range:NSMakeRange(offset, 2)];
	offset += 2;
	result = ntohs(result);
	return result;
}

- (uint32_t) getInt
{
	if (offset >= [Data length]-3) 
		return 0;
	uint32_t result;
	[Data getBytes:&result range:NSMakeRange(offset, 4)];
	offset += 4;
	result = ntohl(result);
	return result;
}

- (NSString *) getString
{
	uint16_t result = [self getShort];
	NSData * str = [self getByteLength:result];
	return [[NSString alloc] initWithData:str encoding:NSUnicodeStringEncoding];
}

- (void) packByte: (uint8_t) newData
{
	[Data appendBytes:&newData length:1];
}

- (void) packBytes: (uint8_t *) newData: (int) count
{
	[Data appendBytes:newData length:count];
}

- (void) packData: (NSData *) newData
{
	[Data appendData:newData];
}

- (void) packShort: (int16_t) newData
{
	int16_t theData = htons(newData);
	[Data appendBytes:&theData length:2];
}

- (void) packShorts: (int16_t *) newData: (int) count
{
	for (int i = 0; i < count; i++)
		[self packShort:newData[i]];
}

- (void) packInt: (int32_t) newData
{
	int32_t theData = htonl(newData);
	[Data appendBytes:&theData length:4];
}

- (void) packInts: (int32_t *) newData: (int) count
{
	for (int i = 0; i < count; i++)
		[self packInt:newData[i]];
}

- (void) packString: (NSString *) newData
{
	NSData * str = [newData dataUsingEncoding:NSUnicodeStringEncoding];
	int16_t len = [str length];
	[self packShort:len];
	[self packData:str];
}

@end
